<?php


namespace App\Dao;


use App\Constants\Model\CooperativeMenuConfig;
use App\Model\Cooperative;

class CooperativeDao extends AbstractDao
{
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        $query = Cooperative::query();
        foreach ($where as $field => $value) {
            switch ($field) {
                case 'ids':
                    $query->whereIn('id', $value);
                    break;
                case 'cooperative_ids':
                    $query->whereIn('id', $value);
                    break;
                case 'cooperative_id':
                    $query->where('id', $value);
                    break;
                case 'keywords':
                    $query->where(function ($query) use ($value) {
                        $query->where('nickname', 'like', '%' . $value . '%');
                        $query->orWhere('phone', $value);
                    });
                    break;
                default:
                    $query->where($field, $value);
                    break;
            }
        }
        return $query;
    }

    public function syncMenuConfigs(Cooperative $cooperative, array $menuConfigIds): array
    {
        return $cooperative->cooperativeMenuConfigs()->sync($menuConfigIds);
    }

    /**
     * @param Cooperative $cooperative
     * @return array
     */
    public function getMenuIds(Cooperative $cooperative): array
    {
        return $cooperative->cooperativeMenus()->get(['id'])->pluck('id')->toArray();
    }

    /**
     * 根据地区获取供应商id
     * @param array $where
     * @return array
     */
    public function getCooperativeIdsByRegion(array $where)
    {
        return $this->where($where)->pluck('id')->toArray();
    }

    /**
     * 判断合作商是否可以审核任务
     * @param int $cooperativeId
     * @return bool true合作商，false母公司
     */
    public function isCanAuditTask(int $cooperativeId): bool
    {
        /** @var Cooperative $cooperative */
        $cooperative = $this->first(['id' => $cooperativeId]);
        $cooperativeMenu = $cooperative->cooperativeMenus()->where(
            'menu_config_id',
            CooperativeMenuConfig::TASK_AUDIT
        )->first();
        return $cooperativeMenu ? true : false;
    }

    /**
     * 根据城市获取合作商列表
     * @param $region
     * @return array
     */
    public function getRegionCooperatives($region)
    {
        $where = ['city' => $region['city_id']];

        return $this->where($where)
            ->select('id', 'nickname as name')
            ->get()->toArray();
    }
}